import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Request,
} from "@nestjs/common";
import { ApiBearerAuth, ApiOperation, ApiTags } from "@nestjs/swagger";
import { Roles } from "src/utils/decorators/roles.guard";
import { JwtPayload } from "src/utils/interfaces/jwt.interface";
import { ClientService } from "./client.service";
import { CreateClientDto } from "./dto/create-client.dto";
import { UpdateClientDto } from "./dto/update-client.dto";

@Controller("client")
@ApiTags("客户")
@ApiBearerAuth()
export class ClientController {
  constructor(private readonly clientService: ClientService) {}

  @Get("list")
  @ApiOperation({
    summary:
      "列出所有客户，如果是管理员，列出所有，如果不是，列出当前用户所在公司的所有客户",
  })
  list(@Request() req) {
    if (req.user.aud === "admin") {
      return this.clientService.findAll();
    } else {
      const companyId = req.user.company;
      return this.clientService.findByCompany(companyId);
    }
  }

  @Get("count")
  @ApiOperation({
    summary:
      "列出所有客户数量，如果是管理员，列出所有，如果不是，列出当前用户所在公司的客户数量",
  })
  count(@Request() req: { user: JwtPayload }) {
    const companyId = req.user.company;
    return this.clientService.count(companyId);
  }

  @Get("last")
  @ApiOperation({
    summary: "找出最后一个新增的客户",
  })
  findLast(@Request() req: { user: JwtPayload }) {
    const companyId = req.user.company;
    return this.clientService.findLast(companyId);
  }

  @Post()
  @Roles("manager")
  @ApiOperation({
    summary: "为当前公司创建客户，只有经理拥有该权限",
  })
  create(@Request() req, @Body() createClientDto: CreateClientDto) {
    const companyId = req.user.company;
    return this.clientService.create(createClientDto, companyId);
  }

  @Get("list/:companyId")
  @Roles("admin")
  @ApiOperation({
    summary: "列出公司id对应的所有客户列表, 只有管理员有此权限",
  })
  listByCompany(@Param("companyId") companyId: string) {
    return this.clientService.findByCompany(companyId);
  }

  @Get(":id")
  @ApiOperation({
    summary: "根据ID查找客户",
  })
  find(@Param("id") id: string) {
    return this.clientService.find(id);
  }

  @Put(":id")
  @Roles("manager", "admin")
  @ApiOperation({
    summary: "为当前公司修改客户信息，只有经理拥有该权限",
  })
  update(@Param("id") id: string, @Body() updateClientDto: UpdateClientDto) {
    return this.clientService.update(id, updateClientDto);
  }

  @Delete(":id")
  @Roles("manager", "admin")
  @ApiOperation({
    summary: "为当前公司删除客户，只有经理拥有该权限, 有订单的客户无法删除",
  })
  remove(@Param("id") id: string) {
    return this.clientService.remove(id);
  }
}
